<?php

namespace backend\controllers;

use common\models\Complaint;
use common\models\JurisdGroup;
use common\models\JurisdUser;
use common\models\Menu;
use common\models\Shop;
use Yii;
use common\models\Admin;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use yii\base\Application;
use yii\base\Module;
use yii\web\Controller;
use yii\web\Cookie;
use common\service\MenuService;
use yii\web\Response;

/**
 * 控制器基类.
 * Class BaseController
 * @package backend\controllers
 */
class BaseController extends Controller
{
    /**
     * 加密所用到的盐,请勿修改,上线时在改
     * @var string
     */
    protected  $salt = 'a321df354sa35d1f';

    /**
     * 所记录的cookie名,请修改成项目名.
     * @var string
     */
    protected  $auth_cookie = "backend_group";

    protected $page_size = 10;
    protected $cookie_captcha_name = 'backend_captcha';

    protected $admin = null;

    protected $allow_actions = [
        'admin/login',
        'admin/logout',
        'index/get-menu',
        'index/get-captcha',
        'error/index'
    ];

    public function __construct($id, Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);
        $view  = \Yii::$app->view;
        $view->params['id'] = $id;
        $this->layout  = "page";
        $this->getView()->title = '后台管理系统';
    }

    /**
     * 这里要初始化权限
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        if(in_array($action->getUniqueId(),$this->allow_actions))
        {
            return true;
        }

        $is_login = $this->checkLoginStatus();

        if(!$is_login)
        {
            if($this->isAjax())
            {
                $this->renderJson(['url'=>GlobalUrlService::buildAdminUrl('/admin/login')],'请重新登录',ConstantService::$response_fail);
            }
            $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
            return false;
        }

        // 这里要检查用户的权限,为rbac埋坑
        if(!in_array($action->getUniqueId(),$this->allow_actions) && $this->admin['id'] != 1)
        {
            $perm = $this->checkPermision($action->getUniqueId());
            if(!$perm){
                if($this->isAjax())
                {
                    $this->renderJson([],'没有权限操作,请联系管理员',ConstantService::$response_fail);
                }
                $this->redirect(GlobalUrlService::buildAdminUrl('/error/index',['msg'=>'没有权限操作,请联系管理员!']));
                return false;
            }
        }
        //获取菜单
//        $this->getmenus($action);
        $this->getMessage();
        return true;
    }

    /**
     * 获取菜单
     * @param $action
     */
    protected function getmenus($action){
        //获取所有菜单 这个地方修改为根据当前用户获取该显示的菜单,
        // 每个具体权限操作的时候还需要验证一次
        if($this->admin['id'] == 1){
            $menus = Menu::find()->where(['is_show'=>1])->asArray()->all();
        }else{

            $menus = $this->checkPermision();
            foreach ($menus as $key=>$item){
                if($menus[$key]['is_show'] == 0){
                    unset($menus[$key]);
                }
            }
            unset($item);

        }
        $menus = MenuService::getMenus($menus);
        $this->getView()->params['menus'] = $menus;

        //获取当前的访问的菜单id
//        $controller = Yii::$app->controller->id;
//        $current_action = Yii::$app->controller->action->id;
//        $url = $controller.'/'.$current_action;
        $url = substr($_SERVER['REQUEST_URI'],1);

        $current = Menu::find()
            ->andWhere(['url'=>$url])
            ->andWhere(['!=','parent_code',0])
            ->asArray()
            ->one();
        $this->getView()->params['menu_current'] = $current;

        //获取页面菜单
        if(!in_array($action->getUniqueId(),$this->allow_actions)){
            $url = $action->getUniqueId();
            $menu = Menu::findOne(['url'=>$url]);
            if(!empty($menu)){
                $current_menus = MenuService::getParentsMenu($menu['menu_id']);
                $current_menus = array_reverse($current_menus);

                $this->getView()->params['current_menu'] = $current_menus;
            }else{
                $this->getView()->params['current_menu'] = [];
            }

        }else{
            $this->getView()->params['current_menu'] = [];
        }
    }

    /**
     * 判断权限
     * @param string $menu
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    private function checkPermision($menu = ''){
        $groups = JurisdUser::find()->where(['admin_id'=>$this->admin['id']])->asArray()->all();
        if(!empty($groups)){
            $roleids = array_column($groups,'group_id');
            $perms = JurisdGroup::find()->where(['group_id'=>$roleids])->asArray()->all();
            if(!empty($perms)){
                $arr = [];
                foreach ($perms as $perm){
                    $ids = explode(',',$perm['group_jurisd_id']);
                    // array_pop($ids);
                    array_merge($arr,$ids);
                }
                if(!empty($ids)){
                    $menus = Menu::find()->where(['menu_id'=>$ids])->asArray()->all();
                }
                if(empty($menu)){
                    return $menus;
                }else{
                    $urls = array_column($menus,'url');
                    if(in_array($menu,$urls)){
                        return true;
                    }else{
                        return false;
                    }
                }

            }
        }
        if(empty($menu)){
            return [];

        }else{
            return false;
        }

    }

    /**
     * 获取消息队列
     */
    private function getMessage(){
        //获取待审核的商家数量
        $shop_count = Shop::find()->where(['status'=>0])->count();
        $this->getView()->params['shop_count'] = $shop_count;


//        //获取未处理的投诉消息
//        $complaint_untreated = Complaint::find()->where(['status'=>0])->count();
//        //处理中的投诉消息
//        $complaint_hand = Complaint::find()->where(['status'=>1])->count();
//
//        $this->getView()->params['complaint_untreated'] = $complaint_untreated;
//        $this->getView()->params['complaint_hand'] = $complaint_hand;


    }


    /**
     * 检查登录状态
     * @return bool
     */
    private function checkLoginStatus()
    {
        $cookie = $this->getCookie($this->auth_cookie);

        if(!$cookie)
        {
            return false;
        }

        list($uid, $token) = explode('#',$cookie);

        if($uid && preg_match('/^\d+$/',$uid))
        {
            $admin_user = Admin::findOne(['id'=>$uid]);

            if(!$admin_user)
            {
                $this->removeCookie($this->auth_cookie);
                return false;
            }

            // 这里要查询一下用户信息.
            $access_token = $this->genToken($admin_user);
            // 这里代表登录成功.
            if($access_token == $token)
            {
                $this->admin = $admin_user;
                $this->getView()->params['current_user'] = $admin_user;
                return true;
            }
        }
        return false;
    }

    /**
     * 生成密钥.
     * @param $admin
     * @return string
     */
    protected function genToken(Admin $admin)
    {
        return md5(md5(implode('-',[
                $admin->primaryKey,
                $admin['email'],
                $admin['created_time'],
                $admin['password'],
            ])) . $this->salt);
    }

    /**
     * 获取cookie值.
     * @param $cookie_name
     * @param string $default
     * @return mixed
     */
    protected function getCookie($cookie_name,$default = '')
    {
        $cookies = Yii::$app->request->getCookies();
        return $cookies->getValue($cookie_name,$default);
    }

    /**
     * 删除Cookie
     * @param $cookie_name
     */
    protected function removeCookie($cookie_name)
    {
        $cookie_target = new Cookie([
            'name' => $cookie_name
        ]);
        $cookies = Yii::$app->response->cookies;
        $cookies->remove( $cookie_target );
    }

    /**
     * 添加cookie
     * @param string $cookie_name
     * @param string $value
     * @param int $expire
     */
    protected function addCookie($cookie_name,$value,$expire = 3600)
    {
        $cookies = Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => $cookie_name,
            'value' => $value,
            'expire' => $expire? ( time() + $expire ):$expire,
            'path' => '/'
        ]));
    }

    /**
     * 判断是否为ajax请求.
     * @return bool|mixed
     */
    public function isAjax()
    {
        return Yii::$app->request->isAjax;
    }

    /**
     * 判断是否为post请求.
     * @return bool|mixed
     */
    public function isPost()
    {
        return Yii::$app->request->isPost;
    }

    /**
     * 判断是否为Get请求.
     * @return bool|mixed
     */
    public function isGet()
    {
        return Yii::$app->request->isGet;
    }

    /**
     * 获取queryString参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function get($key = '',$default = '')
    {
        $query = Yii::$app->request->getQueryParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 获取post提交参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function post($key = '',$default = '')
    {
        $query = Yii::$app->request->getBodyParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 渲染json请求.
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return mixed
     */
    public function renderJson($data = [],$msg = '',$code = -1)
    {
        // 设置响应头信息.
        Yii::$app->response->format = Response::FORMAT_JSON;

        Yii::$app->response->data = [
            'data'  =>  $data,
            'msg'   =>  $msg,
            'code'  =>  $code,
            'req_id'=>  $this->geneReqId()
        ];

        return Yii::$app->end();
    }

    /**
     * 返回pagejson
     * @param array $data
     * @param int $count
     * @param int $code
     * @throws \yii\base\ExitException
     * @return mixed
     */
    public function renderPageJson($data = [],$count = 0,$code = 0)
    {
        // 设置响应头信息.
        Yii::$app->response->format = Response::FORMAT_JSON;

        Yii::$app->response->data = [
            'data'  =>  $data,
            'count'   =>  $count,
            'code'  =>  $code
        ];

        return Yii::$app->end();
    }

    /**
     * 获取唯一值.
     * @return string
     */
    private function geneReqId()
    {
        return uniqid();
    }


}